//
//  AudioRecorderFileManager.m
//  AudioUnitDemo
//
//  Created by ilongge on 2021/9/2.
//

#import "AudioRecorderFileManager.h"
#import "OSStatusCheck.h"

@interface AudioRecorderFileManager()
@property (nonatomic, copy) NSString *recordFilePath;
@end

@implementation AudioRecorderFileManager
/**
 创建音频文件
 */
- (ExtAudioFileRef)createExtAudioFileWithAsbd:(AudioStreamBasicDescription)destinationFormat
{
     
    CFURLRef destinationURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                                            (CFStringRef)(self.recordFilePath),
                                                            kCFURLPOSIXPathStyle,
                                                            false);
    ExtAudioFileRef audioFileRef;
    
    OSStatus status = ExtAudioFileCreateWithURL(destinationURL,
                                                kAudioFileCAFType,
                                                &destinationFormat,
                                                NULL,
                                                kAudioFileFlags_EraseFile,
                                                &audioFileRef);
    CheckStatus(status, @"创建音频文件", YES);
    CFRelease(destinationURL);
    UInt32 codec = kAppleHardwareAudioCodecManufacturer;
    
    status = ExtAudioFileSetProperty(audioFileRef,
                                     kExtAudioFileProperty_CodecManufacturer,
                                     sizeof(codec),
                                     &codec);
    CheckStatus(status, @"设置音频文件解码器", YES);
    
    status = ExtAudioFileSetProperty(audioFileRef,
                                     kExtAudioFileProperty_ClientDataFormat,
                                     sizeof(destinationFormat),
                                     &destinationFormat);
    CheckStatus(status, @"设置音频文件参数", YES);
    return audioFileRef;
}
/**
 创建音频文件
 */
- (NSString *)createAudioFile
{
    NSString *filePath = [self recordFilePath];
    return filePath.copy;
}

/**
 录音文件本地原始路径
 每次开始录音则会按照时间生成一个新的名称
 */
- (NSString*)recordFilePath
{
    if (_recordFilePath == nil) {
        NSString *audioRecordDirPath  = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"audioRecord"];
        
        NSFileManager *manager = [NSFileManager defaultManager];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd_HHmmss";
        formatter.timeZone = [NSTimeZone localTimeZone];
        NSString *audioName = [formatter stringFromDate:[NSDate date]];
        BOOL ret = [manager fileExistsAtPath:audioRecordDirPath];
        if (ret == NO) {
            NSError *error;
            [manager createDirectoryAtPath:audioRecordDirPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error];
        }
        
        NSString *audioPath  = [NSString stringWithFormat:@"%@/%@.pcm", audioRecordDirPath, audioName];
        _recordFilePath = audioPath;
    }
    return _recordFilePath;
}
/**
 写入音频数据到文件
 */
- (void)writeData:(NSData*)data
{
    NSLog(@"追加写入%ldKBytes音频数据", data.length / 1024);
    if (![[NSFileManager defaultManager] fileExistsAtPath:self.recordFilePath]){
        [[NSFileManager defaultManager] createFileAtPath:self.recordFilePath contents:nil attributes:nil];
    }
    NSFileHandle * handle = [NSFileHandle fileHandleForWritingAtPath:self.recordFilePath];
    [handle seekToEndOfFile];
    [handle writeData:data];
    [handle closeFile];
}
/**
 关闭文件
 */
- (NSString *)closeFile:(ExtAudioFileRef)audioFileRef
{
    if (audioFileRef) {
        ExtAudioFileDispose(audioFileRef);
        audioFileRef = nil;
    }
    NSString *recordFilePath = self.recordFilePath.copy;
    _recordFilePath = nil;
    return recordFilePath;
} 
@end
